package com.hopscotch.service.impl;

import com.hopscotch.entity.Attendance;
import com.hopscotch.mapper.AttendanceMapper;
import com.hopscotch.mapper.UserMapper;
import com.hopscotch.service.AttendanceService;
import com.hopscotch.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class AttendanceServiceImpl implements AttendanceService {
    @Autowired
    private AttendanceMapper attendanceMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Attendance> list(Attendance attendance) {
        if (attendance.getAtTime() != null){
            attendance.setAtCreateTime(attendance.getAtTime()[0]);
            attendance.setAtEndTime(attendance.getAtTime()[1]);
            System.out.println( attendance);
        }
        List<Attendance> list = attendanceMapper.list(attendance);
        return list;
    }

    @Override
    public void createTime() {

        LocalDateTime localDateTime = LocalDate.now().atTime(9, 0);
        Attendance attendance = new Attendance();
        String currentUserName = SecurityUtils.getCurrentUserName();
        LocalDate now1 = LocalDate.now();
        //检查是否已经打卡
        Attendance attendance1 = attendanceMapper.listByNameAndData(currentUserName,now1.toString());
        if (attendance1 != null)
        {
            return;
        }
        attendance.setAtUser(currentUserName);
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(localDateTime)){
            attendance.setStatus("迟到");
            userMapper.setLate(currentUserName);
        }else {
            attendance.setStatus("正常上班");
        }
        attendance.setAtCreateTime(now.toString());
        attendanceMapper.createTime(attendance);
    }

    @Override
    public void endTime() {
        LocalDateTime localDateTime = LocalDate.now().atTime(18, 0);
        String currentUserName = SecurityUtils.getCurrentUserName();
        LocalDate now = LocalDate.now();
        Attendance attendance = attendanceMapper.listByNameAndData(currentUserName,now.toString());
        System.out.println(attendance);
        if (attendance != null && attendance.getAtEndTime() == null){
            if (LocalDateTime.now().isAfter(localDateTime)){
                attendance.setStatus(attendance.getStatus() + "正常下班");
            }else if (LocalDateTime.now().isBefore(localDateTime)){
                attendance.setStatus(attendance.getStatus() + "早退");
                userMapper.setEarly(currentUserName);
            }
            attendance.setAtEndTime(LocalDateTime.now().toString());
            attendanceMapper.endTime(attendance);
        }

    }
}
